package com.gpt.baidu.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/baidu","/api/baidu"})
public class BaiduGptController {

    //百度的API_KEY
    private String  API_KEY = "API_KEY";

    //百度的SECRET_KEY
    private String  SECRET_KEY = "SECRET_KEY";

    /**
     * 文心一言返回收到信息后的结果
     *
     * @param chat 前端传入的json格式信息
     * @return
     */
    @RequestMapping(value= {"/chat"})
    @ResponseBody
    public String ChatMessage (@RequestBody JSONObject chat){
        String message = null;
        try {
            String token = getAccessToken();
            String json = chat.toString();
            String res = HttpUtil.post("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + token,
                    json);
            message = new JSONObject(res).get("result").toString();
            System.out.println(message);
        } catch (Exception e) {
            message = "获取信息失败，请重新请求";
            System.out.println(e.getMessage());
        }
        return message;
    }

    /**
     * 根据API_KEY和SECRET_KEY 获取token信息
     *
     * @return
     */
    public String getAccessToken()  {
        String res= HttpUtil.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=" +
                "client_credentials&client_id="+API_KEY+"&client_secret="+SECRET_KEY);
        JSONObject jsonObject = new JSONObject(res);
        String token = jsonObject.get("access_token").toString();
        return token;
    }

}
